package com.imu.purse.modules.trade.service.impl;

import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.imu.common.exception.ErrorDesc;
import com.imu.common.exception.RRException;
import com.imu.common.utils.R;
import com.imu.core.base.BaseService;
import com.imu.enums.OrderTypeStatus;
import com.imu.enums.PStatus;
import com.imu.enums.TradeType;
import com.imu.purse.modules.bitcoin.BitcoinApi;
import com.imu.purse.modules.trade.dao.FundMapper;
import com.imu.purse.modules.trade.dao.TradeInfoMapper;
import com.imu.purse.modules.trade.dao.TradeLogMapper;
import com.imu.purse.modules.trade.entity.FundEntity;
import com.imu.purse.modules.trade.entity.TradeInfoEntity;
import com.imu.purse.modules.trade.entity.TradeLogEntity;
import com.imu.purse.modules.trade.form.ConversionForm;
import com.imu.purse.modules.trade.form.ExchangeForm;
import com.imu.purse.modules.trade.service.FundService;
import com.imu.purse.modules.trade.service.TradeLogService;
import com.xiaoleilu.hutool.util.ArrayUtil;
import com.xiaoleilu.hutool.util.NumberUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 交易流水
 * @author sunhongwei
 * @email sunhongwei@jshijian.com
 * @date 2018-03-22 10:33:21
 * Copyright (c) 2017 武汉极时间科技有限公司 版权所有 
 * Jshijian aloha CO.,LTD. All Rights Reserved. 
 */
@Service
public class TradeLogServiceImpl extends BaseService<TradeLogEntity> implements TradeLogService 
{
	@Override
    @Transactional
    public int save(final TradeLogEntity tradeLog)
	{
    	return super.insert(tradeLog);
	}
	
	@Override
	@Transactional
    public int update(final TradeLogEntity tradeLog) 
    {
    	return mapper.updateByPrimaryKeySelective(tradeLog);
    }
    
    @Override
	@Transactional
    public int saveUpdate(final TradeLogEntity tradeLog)
    {
    	int len = 0;
    	
    	if(1 > (len = this.update(tradeLog)))
    	{
        	len = this.insert(tradeLog);
    	}
    	
    	return len;
    }
    
 	@Override
	@Transactional
    public boolean delete(final String ...ids)
    {
    	if(ArrayUtil.isEmpty(ids)) return false;
    	
    	for (String id : ids) 
    	{
    		if(StrUtil.isBlank(id)) continue;
    		
    		if(NumberUtil.isNumber(id))
    		{
        		mapper.deleteByPrimaryKey(Long.valueOf(id));
    		}
		}
    	
    	return true;
    }
    
    @Override
    public TradeLogEntity findById(final Long id)
    {
    	if(null == id) return null;
    	return mapper.selectByPrimaryKey(id);
    }
    
    @Override
    public List<TradeLogEntity> queryList(final TradeLogEntity tradeLog)
    {
    	if (tradeLog.getPage() != null && tradeLog.getLimit() != null)
    	{
            PageHelper.startPage(tradeLog.getPage(), tradeLog.getLimit());
        }
    	
    	return mapper.findByPage(tradeLog);
    }
    
    @Override
	@Transactional
    public R conversion(final ConversionForm form, final Long userId,String sign)
    {

		FundEntity fund = fundService.findByUserId(userId);
		if(null == fund) {
			throw new RRException(ErrorDesc.GET_USER_ERR.getMsg(), ErrorDesc.GET_USER_ERR.getCode());
		}
    	//更新用户钱包
    	FundEntity fEntity = new FundEntity();
    	fEntity.setUserId(userId);
    	//扣除20% IMU，80% GET
    	fEntity.setMoney(form.getImuMoney());
    	fEntity.setLocketh(form.getXlcMoney());
    	fEntity.setTimeUpdate(new Date());
    	if(fundMapper.updateMoneyByUId(fEntity) > 0){//代表该用户金额够
			List<TradeInfoEntity> infoList  = Lists.newArrayList();
			//保存转账记录  IMU
			TradeInfoEntity info =  new TradeInfoEntity();
			info.setMoney(form.getImuMoney());
			info.setOrderNo(form.getOrderNo());
			info.setDetail(form.getDetail());
			info.setPayUserId(userId);
			info.setOrderState(PStatus.Finished.getType());
			info.setOrderType(OrderTypeStatus.CONVERSION.getType());
			info.setOrderNo(form.getOrderNo());
			info.setOrderCreate(new Date());
			info.setSmoney(fund.getMoney());
			info.setEmoney(fund.getMoney().subtract(form.getImuMoney()));
			info.setYtfType(TradeType.IMU.getType());

			infoList.add(info);
			//GET 记录
			info =  new TradeInfoEntity();
			info.setMoney(form.getXlcMoney());
			info.setOrderNo(form.getOrderNo());
			info.setDetail(form.getDetail());
			info.setPayUserId(userId);
			info.setOrderState(PStatus.Finished.getType());
			info.setOrderType(OrderTypeStatus.CONVERSION.getType());
			info.setOrderNo(form.getOrderNo());
			info.setOrderCreate(new Date());
			info.setYtfType(TradeType.LOCK_ETH.getType());
			info.setSmoney(fund.getLocketh());
			info.setEmoney(fund.getLocketh().subtract(form.getXlcMoney()));
			infoList.add(info);
			tradeInfoMapper.insertList(infoList);

			//调用GET的数据
			/*String result = HttpUtil.doPost(form.getXlcUrl(),JSON.toJSONString(form),sign);
			if(StringUtils.isNotEmpty(result)){
				R r = JSON.parseObject(result,R.class);
				if(Integer.valueOf(r.get("code").toString()) != 1){
					fundMapper.deleteByPrimaryKey(fEntity);
					tradeInfoMapper.deleteByPrimaryKey(info);
				}
				return r;
			}else{
				//删除imu创建的记录
				fundMapper.deleteByPrimaryKey(fEntity);
				tradeInfoMapper.deleteByPrimaryKey(info);
				return R.error(-2,"GET金额不够");
			}*/
            //调用
		}else{
    		return R.error(0,"IMU或GET金额不够");
		}
		return R.error(1,"兑换成功");
    }

	@Override
	@Transactional
	public R exchange(ExchangeForm form, Long userId, String sign) {

		FundEntity fund = fundService.findByUserId(userId);
		if(null == fund) {
			throw new RRException(ErrorDesc.GET_USER_ERR.getMsg(), ErrorDesc.GET_USER_ERR.getCode());
		}

		//更新用户钱包
		FundEntity fEntity = new FundEntity();
		fEntity.setUserId(userId);
		//扣除20% IMU，80% GET
		fEntity.setMoney(form.getMoney());
		fEntity.setTimeUpdate(new Date());
		fEntity.setYtfType(form.getYtfType());
		if(fundMapper.updateMoneyByUIdAndYtype(fEntity) > 0){//代表该用户金额够
			List<TradeInfoEntity> infoList  = Lists.newArrayList();
			//保存转账记录  IMU
			TradeInfoEntity info =  new TradeInfoEntity();
			info.setMoney(form.getMoney());
			info.setOrderNo(form.getOrderNo());
			info.setDetail(form.getDetail());
			info.setPayUserId(userId);
			info.setOrderState(PStatus.Finished.getType());
			info.setOrderType(OrderTypeStatus.EXCHANGE.getType());
			info.setOrderNo(form.getOrderNo());
			info.setOrderCreate(new Date());

			if(form.getYtfType() == 4) {
				info.setYtfType(TradeType.LOCK_ETH.getType());
				info.setSmoney(fund.getLocketh());
				info.setEmoney(fund.getLocketh().add(form.getMoney()));
			}
			else if (form.getYtfType() == 5) {
				info.setYtfType(TradeType.LOCK_COWRY.getType());
				info.setSmoney(fund.getLockcowry());
				info.setEmoney(fund.getLockcowry().add(form.getMoney()));
			}
			else {
				throw new RRException("兑换类型不正确", 0); //为了控制事物
			}

			infoList.add(info);
			tradeInfoMapper.insertList(infoList);
		}else{
			return R.error(0,"合盈分兑换失败");
		}
		return R.error(1,"兑换成功");
	}

	@Override
	public int checkConvsion(String orderNo, Long id) {
		Map<String,Object> map = new HashMap<>();
		map.put("orderNo",orderNo);
		map.put("userId",id);
		return tradeInfoMapper.checkConvsion(map);
	}

	@Autowired
	private TradeLogMapper mapper;

	
	@Autowired
	private TradeInfoMapper tradeInfoMapper;
	
	@Autowired
	private FundMapper fundMapper;

	@Autowired
	private BitcoinApi bitcoinApi;

	@Autowired
	private RedisTemplate<String,String> redisTemplate;

	@Autowired
	private FundService fundService;
}
